﻿using MediatR;
using Microsoft.EntityFrameworkCore;
using RearLivestock.Common.Domains.hq;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.RBAC.Api.Application.hqApplication.Commands.Departmentss
{
    public class SearchDepartmentTypeHandler : IRequestHandler<SearchDepartmentTypeCommand, Result<List<DepartmentType>>>
    {
        /// <summary>
        /// 部门类别
        /// </summary>
        private readonly IBaseRepository<DepartmentType> _departmentTypeRepository;

        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<SearchDepartmentTypeHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="departmentTypeRepository"></param>
        /// <param name="logger"></param>
        public SearchDepartmentTypeHandler(IBaseRepository<DepartmentType> departmentTypeRepository,
             ILogger<SearchDepartmentTypeHandler> logger)
        {
            _departmentTypeRepository = departmentTypeRepository;
            _logger = logger;
        }

        /// <summary>
        /// 业务逻辑
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<List<DepartmentType>>> Handle(SearchDepartmentTypeCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<List<DepartmentType>>() { Code = (int)CommonErrorCode.Search };
            try
            {
                var query = await (await _departmentTypeRepository.GetAll()).ToListAsync();
                if (query.Count != 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                    result.Data = query;
                    result.Msg = "获取部门类别成功";
                }
            }
            catch (Exception ex)
            {
                result.Msg = "获取部门类别异常" + ex.Message;
                _logger.LogError("获取部门类别异常" + ex.Message);
            }
            return result;
        }
    }
}
